package com.fzkj.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    /**
     * 1.创建socket对象，指定端口
     * 2.
     */

    public static void main(String[] args)   {
        // 创建socket
        ServerSocket serverSocket = null;
        Socket socket = null;
        BufferedReader reader = null;
        try {
            serverSocket = new ServerSocket(9999);
            System.out.println("服务已经启动~~");
            // 接受客户端的socket
            socket = serverSocket.accept();

            // 获得流对象
            InputStream in = socket.getInputStream();
            reader = new BufferedReader(new InputStreamReader(in));

            // 读取数据
            while(true){
                String line = reader.readLine();
                if ("退出".equals(line)){
                    break;
                }
                InetAddress address = serverSocket.getInetAddress();
                String  ip = address.getHostAddress();
                System.out.println(ip+"发送了："+line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {

                try {
                    if (reader != null){
                        reader.close();
                    }
                    if(socket != null){
                        socket.close();
                    }
                    if(serverSocket != null){
                        serverSocket.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

        }
    }
}
